package com.app.reactnativelearnmodule

import android.os.Bundle
import android.view.KeyEvent
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.facade.annotation.Route
import com.facebook.react.ReactRootView
import com.facebook.react.ReactActivity
import com.facebook.react.shell.MainReactPackage
import com.facebook.react.ReactInstanceManager
import com.facebook.react.bridge.JSBundleLoader
import com.facebook.react.common.LifecycleState
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler


/**
 *  Create by zhouwd on 2020-02-21
 *  Describe:
 */
@Route(path = "/react_native_learn_module/react_native_learn_activity")
class ReactNativeLearnActivity : AppCompatActivity(), DefaultHardwareBackBtnHandler {

    private var mReactInstanceManager: ReactInstanceManager? = null

    private var mReactRootView: ReactRootView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mReactRootView = ReactRootView(this)

        //val bundle = JSBundleLoader.createDeltaFromNetworkLoader()

        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(application)
                .setCurrentActivity(this)
                .setBundleAssetName("index.android.bundle")
                .setJSMainModulePath("index")
                .addPackage(MainReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build()

        // 注意这里的MyReactNativeApp必须对应“index.js”中的
        // “AppRegistry.registerComponent()”的第一个参数
        mReactRootView!!.startReactApplication(mReactInstanceManager, "ReactNativeLearn", null)

        setContentView(mReactRootView)

    }

    override fun invokeDefaultOnBackPressed() {
        super.onBackPressed()
    }

    override fun onPause() {
        super.onPause()
        mReactInstanceManager?.onHostPause(this)
    }

    override fun onResume() {
        super.onResume()
        mReactInstanceManager?.onHostResume(this, this)
    }

    override fun onDestroy() {
        super.onDestroy()
        mReactInstanceManager?.onHostDestroy(this)
        mReactRootView?.unmountReactApplication()
    }

    override fun onBackPressed() {

        if (mReactInstanceManager == null) {
            super.onBackPressed()
        } else {
            mReactInstanceManager?.onBackPressed()
        }
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        mReactInstanceManager?.let {
            if (keyCode == KeyEvent.KEYCODE_MENU) {
                it.showDevOptionsDialog()
                return true
            }
        }
        return super.onKeyUp(keyCode, event)
    }

}